import { useEffect, useState } from 'react';

export interface Message {
  role: 'user' | 'assistant' | 'system';
  content: string;
}

export interface ChatSession {
  id: string;
  title: string;
  messages: Message[];
  contextId: string; // 用于标识上下文，例如：repo-username-repoName, doc-docId等
  createdAt: number;
  updatedAt: number;
}

// 缓存键前缀
const STORAGE_KEY = 'gitdiagram-chat-sessions';

/**
 * 根据不同的上下文生成上下文ID
 */
export const generateContextId = (params: {
  repoUrl?: string;
  documentId?: string;
  codeId?: string;
}): string => {
  const { repoUrl, documentId, codeId } = params;
  
  if (documentId) return `doc-${documentId}`;
  if (codeId) return `code-${codeId}`;
  if (repoUrl) {
    // 从repoUrl提取用户名和仓库名
    try {
      const urlParts = repoUrl.split('/');
      const repoIndex = urlParts.findIndex(part => part === 'github.com');
      if (repoIndex >= 0 && urlParts.length >= repoIndex + 3) {
        const username = urlParts[repoIndex + 1];
        const repo = urlParts[repoIndex + 2]?.split('#')[0]?.split('?')[0] || '';
        return `repo-${username}-${repo}`;
      }
    } catch (e) {
      console.error('解析仓库URL时出错:', e);
    }
  }
  
  return 'global'; // 如果没有特定上下文，使用全局上下文
};

/**
 * 聊天会话管理Hook
 */
export default function useChatSessions(contextParams: {
  repoUrl?: string;
  documentId?: string;
  codeId?: string;
}) {
  const contextId = generateContextId(contextParams);
  const [sessions, setSessions] = useState<ChatSession[]>([]);
  const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
  
  // 加载会话
  useEffect(() => {
    if (typeof window !== 'undefined') {
      try {
        // 从localStorage加载会话
        const storedSessions = localStorage.getItem(STORAGE_KEY);
        const parsedSessions: ChatSession[] = storedSessions ? JSON.parse(storedSessions) : [];
        
        // 过滤出当前上下文的会话
        const contextSessions = parsedSessions.filter(session => session.contextId === contextId);
        setSessions(contextSessions);
        
        // 如果有会话，设置最近的一个为活动会话
        if (contextSessions.length > 0) {
          const sortedSessions = [...contextSessions].sort((a, b) => b.updatedAt - a.updatedAt);
          setActiveSessionId(sortedSessions[0]?.id || null);
        } else {
          setActiveSessionId(null);
        }
      } catch (error) {
        console.error('加载聊天会话时出错:', error);
        // 出错时重置会话
        setSessions([]);
        setActiveSessionId(null);
      }
    }
  }, [contextId]);
  
  // 保存会话到localStorage
  const saveSessions = (updatedSessions: ChatSession[]) => {
    try {
      // 从localStorage获取所有会话
      const storedSessions = localStorage.getItem(STORAGE_KEY);
      const allSessions: ChatSession[] = storedSessions ? JSON.parse(storedSessions) : [];
      
      // 过滤出不属于当前上下文的会话
      const otherSessions = allSessions.filter(session => session.contextId !== contextId);
      
      // 合并其他会话和更新后的当前上下文会话
      const combinedSessions = [...otherSessions, ...updatedSessions];
      
      // 保存回localStorage
      localStorage.setItem(STORAGE_KEY, JSON.stringify(combinedSessions));
      
      // 更新状态
      setSessions(updatedSessions);
    } catch (error) {
      console.error('保存聊天会话时出错:', error);
    }
  };
  
  // 创建新会话
  const createSession = (initialMessage?: Message): string => {
    const newSession: ChatSession = {
      id: `session-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
      title: '新对话',
      messages: initialMessage ? [initialMessage] : [],
      contextId,
      createdAt: Date.now(),
      updatedAt: Date.now()
    };
    
    const updatedSessions = [...sessions, newSession];
    saveSessions(updatedSessions);
    setActiveSessionId(newSession.id);
    
    return newSession.id;
  };
  
  // 获取活动会话
  const getActiveSession = (): ChatSession | null => {
    if (!activeSessionId) return null;
    return sessions.find(session => session.id === activeSessionId) || null;
  };
  
  // 更新会话消息
  const updateSessionMessages = (sessionId: string, messages: Message[]) => {
    const updatedSessions = sessions.map(session => {
      if (session.id === sessionId) {
        // 根据第一条用户消息更新会话标题
        const firstUserMessage = messages.find(msg => msg.role === 'user');
        const content = firstUserMessage?.content || '';
        
        let title = '新对话';
        if (content) {
          const firstLine = content.split('\n')[0] || '';
          title = firstLine.substring(0, 30) + (firstLine.length > 30 ? '...' : '');
        }
        
        return {
          ...session,
          messages,
          title,
          updatedAt: Date.now()
        };
      }
      return session;
    });
    
    saveSessions(updatedSessions);
  };
  
  // 删除会话
  const deleteSession = (sessionId: string) => {
    const updatedSessions = sessions.filter(session => session.id !== sessionId);
    saveSessions(updatedSessions);
    
    // 如果删除的是当前活动会话，则将最新的会话设为活动
    if (sessionId === activeSessionId && updatedSessions.length > 0) {
      const sortedSessions = [...updatedSessions].sort((a, b) => b.updatedAt - a.updatedAt);
      setActiveSessionId(sortedSessions[0]?.id || null);
    } else if (updatedSessions.length === 0) {
      setActiveSessionId(null);
    }
  };
  
  // 切换活动会话
  const setActiveSession = (sessionId: string) => {
    if (sessions.some(session => session.id === sessionId)) {
      setActiveSessionId(sessionId);
      return true;
    }
    return false;
  };
  
  // 重命名会话
  const renameSession = (sessionId: string, newTitle: string) => {
    const updatedSessions = sessions.map(session => {
      if (session.id === sessionId) {
        return {
          ...session,
          title: newTitle,
          updatedAt: Date.now()
        };
      }
      return session;
    });
    
    saveSessions(updatedSessions);
  };
  
  return {
    sessions,
    activeSessionId,
    createSession,
    getActiveSession,
    updateSessionMessages,
    deleteSession,
    setActiveSession,
    renameSession
  };
} 